package br.com.usjt.component.commons.login.util;

import static br.com.usjt.component.commons.login.util.ValidationUtil.isNull;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import br.com.usjt.component.commons.login.exceptions.EncryptException;

public abstract class SHAConverter {

    private SHAConverter() {
    }

    public static String encrypts(String password) {

        validarSenha(password);
        try {

            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            byte[] hash = messageDigest.digest(password.getBytes("UTF-8"));

            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < hash.length; i++) {
                stringBuilder.append(Integer.toString((hash[i] & 0xff) + 0x100, 16).substring(1));
            }
            return stringBuilder.toString();

        } catch (NoSuchAlgorithmException ex) {
            throw new EncryptException(ex);
        } catch (UnsupportedEncodingException unsupportedEncodingException) {
            throw new EncryptException(unsupportedEncodingException);
        }
    }

    private static void validarSenha(String value) {
        if ("".equalsIgnoreCase(value) || isNull(value)) {
            throw new IllegalArgumentException("Valor Invalido");
        } else if (value.length() < 4) {
            throw new IllegalArgumentException("Tamanho Minimo para senha é de 4");
        }

    }
}
